package controler;

import java.util.Date;
import java.sql.SQLException;
import java.util.Vector;

import view.VControler;
import model.Booking;
import model.DBControler;

public class BLControler {
	private DBControler dbControler;
	private VControler vControler;
	private Booking booking;

	public void setDBControler(DBControler ctrl){
		dbControler = ctrl;
	}
	
	public void setVControler(VControler ctrl){
		vControler = ctrl;
	}
	
	public void deleteBooking(){
		throw new RuntimeException("Not yet implemented");
	}
	
	public void bookingValues(String description, String resource, String sign, Date date){
		if(booking == null){
			booking = new Booking();
		}
		
		booking.setDescription(description);
		booking.setResource(resource);
		booking.setSign(sign);
		booking.setDate(date);
		
		
		Booking other = null;
		try {
			other = dbControler.retrieveSelection(booking);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			vControler.setMainStatus("Cannot read bookings: " + e.getLocalizedMessage());
			vControler.showMainDisplay();
			return;
		}
		// TODO: Handle multiple double bookings?
		if(other != null){
			if(!vControler.showDoubleBookingDisplay()){
				vControler.showNewBookingDisplay();
				return;
			}
		}
		
		try {
			dbControler.saveBooking(booking);
			vControler.setMainStatus("Booking saved");
			vControler.showMainDisplay();
		} catch (SQLException sqle){
			sqle.printStackTrace();
			vControler.setMainStatus("Cannot save booking: " + sqle.getLocalizedMessage());
			vControler.showMainDisplay();
		}
	}
	
	public boolean getEditUser(){
		return true; // TODO: User control not implemented
	}
	
	public boolean newBooking(){
		booking = null;
		vControler.showNewBookingDisplay();
		return false;
	}
	
	public Vector<Booking> getAllBookings(){
		return dbControler.allRecords();
	}
}
